/*
 * @Author: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @Date: 2022-03-24
 * @LastEditors: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @LastEditTime: 2022-07-14 11:49:20
 * @Description: 
 * @Administrator: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @Copyright: 文件版本号
 */

import { uploadFile, requestFilePath } from "../../common/api/file-request.js";
import FeedBackApi from '../../common/api/ctn/feedback.api.js';
import doT from '../../../../public/vendor/template/doT.js';

/**
 *@file意见反馈
 *@Date :2022-03-24 13:26:28
 *@create周润玉
*/
(function (window, document, $) {
    'use strict';
    let _allUploadFiles = [];
    $('body').attr('data-weui-theme', 'light'); // 强制光明模式

    let _vm;
    let uploader = null;
    const _json = Utils.ParsingUrl(window.location);
    let defaultToken = JSON.parse(Utils.GetSessionStorage('SNUserInfo'));

    $(function () {
        _vm = new Vue({
            el: "#main-feedback",
            data() {
                return {
                    uploadCount: 0,
                    images: [],///处理weui自带上传插件回显重新上传时的问题
                }
            },
            methods: {
                truckLoadingTime: function (param) {
                    // 保存当前的滚动距离
                    scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                    // 设置 fixed 布局
                    document.body.style.position = 'fixed';
                    document.body.style.height = '100%';
                    document.body.style.width = '100%';
                }
            }
        });

        initCommand();
        uploadInit();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px'
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px'
        });
    });

    //TODO : 命令初始化
    //Date :2022-03-24 13:26:28
    //create周润玉   
    const initCommand = () => {
        //let _json = Utils.ParsingUrl(window.location);
        $('#categoryShow').text('');
        $('#categoryShow').text(_json.category);
        //开关触发事件
        $('#switchChange').on('change', function () {
            let switchClick = $(this).is(':checked');
            if (switchClick == false) { //实名
                $('#messageContent').css('display', 'block');
            } else {
                $('#name').val('');
                $('#phone').val('');
                $('#messageContent').css('display', 'none');
            }
        });

        //提交事件
        $('#feedbackSubmit').on('click', function () {
            let phoneReg = /^1[3456789]\d{9}$/;
            let chinaName = /^[\u4e00-\u9fa5]+$/;
            let notHtml = !(/<\/?[a-zA-Z]+("[^"]*"|'[^']*'|[^'">])*>/.test($('#content').val()));
            let pattern = new RegExp(/[\'\`\╳\~\@\#\$\%\^\&\*\(\)\_\+\~\!\@\#\￥\%\…\…\&\*\（\）\——\=\·\-\{\}\:\"\|\<\>\【\】\\\；\’\‘\?\》\《\：\.\/]|(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f])|(\ud83d[\ude80-\udeff])/);
            let special = pattern.test($('#content').val());

            let switchClick = $('#switchChange').is(':checked');//判断开/关
            if (!Utils.IsNotNull($('#content').val())) {
                return $.toptip('请输入建议或意见', 'warning');
            }
            if (notHtml == false) {
                return $.toptip('请勿输入 html 标签', 'warning');
            } else if (special == true) {
                return $.toptip('请勿输入特殊字符或代码片段', 'warning');
            }
            if (switchClick == false) {
                if (!Utils.IsNotNull($('#name').val()) || !Utils.IsNotNull($('#phone').val())) {
                    return $.toptip('需要解决问题请输入姓名和电话号码', 'warning');
                }
                if (!phoneReg.test($('#phone').val())) {
                    return $.toptip('请输入有效的手机号码', 'warning');
                } else if (!chinaName.test($('#name').val())) {
                    return $.toptip('请输入有效的中文姓名', 'warning');
                }
            }

            let fData = new FormData();
            if (Utils.IsNotNull($('#name').val())) {
                fData.append("name", $('#name').val());
            }
            if (Utils.IsNotNull($('#phone').val())) {
                fData.append("mobileNO", $('#phone').val());
            }
            fData.append("content", $('#content').val());
            fData.append("typeEnum", _json.id);
            fData.append("typeValue", _json.category);
            fData.append("wechatAppId", 'wx59f221dc7f8033b7');
            //  _json.appid
            fData.append("openId", defaultToken.openid);
            if (Utils.IsNotNull(defaultToken.unionid)) {
                fData.append("unionId", defaultToken.unionid || '');
            }

            $.each(_allUploadFiles, function (i, v) {
                fData.append("pic" + (i + 1), v);
            });
            $.showLoading('提交中..');
            $.ajax({
                "type": "POST",
                "url": Utils.CurDomain.FeedBackUrl + '/yyfeedbacks',
                "headers": {
                    "Authorization": "Bearer " + Utils.GetSessionStorage('SNAuthAT'),
                    "Accept": "application/json",
                },
                "data": fData,
                "enctype": 'multipart/form-data',
                "contentType": false,
                "processData": false,
                "cache": false,
                "success": function (res) {
                    if (res.isSucceed == true) {
                        $.toast("提交成功");
                        location.href = '../feedback/backresult.html';
                    }
                },
                "error": Utils.AjaxError
            });
        });

        //返回按钮返回类别事件
        $('#returnCategory').on('click', function () {
            //history.go(-1);
            let count = $('#uploadCount').text();
            if (Utils.IsNotNull($('#content').val()) || $('#name').val() || $('#phone').val() || count != '0') {
                $.confirm({
                    title: '<span style="font-size: 20px">提示</span>',
                    text: '<div class="weui-cell__hd"><i class="weui-icon-info weui-icon_msg"></i></div>' +
                        '<span>存在内容还未提交，返回后填写的数据将会清空！是否确认返回类型选择界面？</span>',
                    onOK: function () {
                        //点击确认
                        location.href = '../../../../html/features/biz/feedback/checkcategory.html?type=' + _json.id + '&state=' + _json.state + '';
                    },
                    onCancel: function () {
                    }
                });
            } else {
                location.href = '../../../../html/features/biz/feedback/checkcategory.html?type=' + _json.id + '&state=' + _json.state + '';
            }
        });

        //限制输入框字数和显示输入字数
        $('#content').bind('input propertychange', function () {
            let fizeNum = $(this).val().length;//获取输入字数
            if (fizeNum > 500) {//如果大于500
                let char = $(this).val();
                char = char.substr(0, 500);//截取字符串（前500）
                $(this).val(char);
                fizeNum = 500;
            }
            $(this).parent().find('.contentcount').text(fizeNum);
        });
    };


    //TODO : 附件上传
    //Date :2022-03-24 13:26:28
    //create周润玉
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                //$.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
                _allUploadFiles.push(files[0]);
                getPictureBase64(files, this.name);
            },
            onQueued: function () {
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-url', _vm.images[i].url);
                    $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                });
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;

            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            let deleteFiles = _allUploadFiles.filter(s => s.id != _id);

                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            _allUploadFiles = deleteFiles;
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    const getPictureBase64 = (file, name) => {
        // return new Promise((resolve, reject) => {
        //   const reader = new FileReader();
        //   reader.readAsDataURL(file);
        //   reader.onload = () => resolve(reader.result);
        //   reader.onerror = (error) => reject(error);
        // });
        var reader = new FileReader();
        reader.readAsDataURL(file[0]);
        reader.onload = function (e) {
            let _list = _vm.images;
            _list.push({
                id: $("#uploaderFiles li").length,
                url: this.result,
                name: name
            });
        }
    };

})(window, document, jQuery)